package com.ruicar.afs.cloud.basic.proceeds.debit.service.impl.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * <p>Description: </p>
 *
 * @author ZC.GUO
 * @version 1.0
 * @date create on 2020-06-27 13:36
 */
@Slf4j
public class ThreadPool {
    private static ThreadPool threadPool = null;
    private ThreadPoolExecutor threadPoolExecutor = null;

    public static ThreadPool getThreadPool(String poolName,int maxThread) {

        if (threadPool == null) {
            synchronized (ThreadPool.class) {
                if (threadPool == null) {
                    threadPool = new ThreadPool(poolName,maxThread);
                }
            }
        }
        return threadPool;
    }

    private ThreadPool(String poolName,int maxThread) {
        threadPoolExecutor = new ThreadPoolExecutor( maxThread,maxThread*3,5,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(maxThread),
                new ThreadPoolExecutor.CallerRunsPolicy());
    }

    public void process(Runnable target) {
        try{
            threadPoolExecutor.execute(target);
        }catch(Exception ex){
            log.error(ex.getMessage());
        }
    }
    public Future<Integer> callProcess(Callable<Integer> task) {
        Future<Integer> flag = null;
        try{
            flag =  threadPoolExecutor.submit(task);
        }catch(Exception ex){
            log.error(ex.getMessage());
        }
        return flag;
    }

    public void shutDown(){
        threadPoolExecutor.shutdown();
    }

    public static ThreadPool getThreadPool() {

        if (threadPool == null) {
            synchronized (ThreadPool.class) {
                if (threadPool == null) {
                    threadPool = new ThreadPool("defaultThread",5);
                }
            }
        }
        return threadPool;
    }

}
